package cn.net.isir.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cn.net.isir.common.RequestObject;
import cn.net.isir.common.ResultObject;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.util.Base64;
import java.util.Map;

/**
 * @author liuxubo
 * @filename RequestUtils.java
 * @package cn.net.isir.common
 * @email lxb@isir.net.cn
 * @date 2018/08/29
 * @comment
 * @since 1.7
 */
public class RequestUtils {

    private static Logger logger = Logger.getLogger(RequestUtils.class);

    /**
     * 检查传入参数字段
     *
     * @param obj         传入参数
     * @param reqParamMap 解码后数据存放地
     * @param names       字段名列表
     * @return 解码结果
     */
    public static ResultObject parametersCheck(RequestObject obj, Map<String, Object> reqParamMap, String[] names) {
        ResultObject ro = new ResultObject();
        Map<String, Object> reqParamMap2;
        logger.info("request res data:" + obj);
        if (obj == null) {
            ro.setMessage("所有请求参数都为空");
            ro.setResult(500);
            return ro;
        }
        if (obj.getData() == null || obj.getData().length() == 0 || "".equals(obj.getData())) {
            ro.setMessage("所有请求参数都为空");
            ro.setResult(500);
            return ro;
        }
        try {
            reqParamMap2 = JSON.parseObject(new String(Base64.getDecoder().decode(obj.getData()), "UTF-8"));
            logger.info("request parsed data:" + reqParamMap2);
        } catch (Exception ex) {
            ro.setMessage("请求参数解析失败");
            ro.setResult(500);
            return ro;
        }
        if (reqParamMap2 == null) {
            ro.setMessage("请求参数解析失败");
            ro.setResult(500);
            return ro;
        }
        if (reqParamMap2.size() == 0) {
            ro.setMessage("请求参数解析失败");
            ro.setResult(500);
            return ro;
        }
        if (reqParamMap2.get("client") == null) {
            ro.setMessage("缺少参数[client]");
            ro.setResult(500);
            return ro;
        }
        String client = String.valueOf(reqParamMap2.get("client"));
        if (!"wx".equals(client) && !"alipay".equals(client)) {
            ro.setMessage("参数[client]类型错误");
            ro.setResult(500);
            return ro;
        }

        for (String name : names) {
            if (reqParamMap2.get(name) == null ||
                    StringUtils.isBlank(String.valueOf(reqParamMap2.get(name)))) {
                ro.setResult(500);
                ro.setMessage("缺失参数[" + name + "]");
                return ro;
            }
            if ("unionid".equals(name)) {
                if ("null".equals(reqParamMap2.get(name))) {
                    ro.setResult(500);
                    ro.setMessage("参数[unionid]不正确");
                    return ro;
                }
            }
        }
        reqParamMap.putAll(reqParamMap2);
        ro.setResult(200);
        ro.setMessage("success");
        return ro;
    }

    /**
     * 判断字符串是否符合标准
     *
     * @param str       子参数
     * @param t         子类对象
     * @param classType 子类型
     * @param names     需要判断的类型
     * @param <T>       需要转换的各种对象
     * @return 转换结果
     */
    public static <T> ResultObject paramConvert(String str, Class<T> classType, T t, String[] names) {
        ResultObject ro = new ResultObject();
        JSONObject jo = new JSONObject();
        try {
            jo = JSON.parseObject(str);
        } catch (Exception ex) {
            ro.setResult(500);
            ro.setMessage("参数解析失败");
        }
        for (String name : names) {
            if (jo.get(name) == null ||
                    StringUtils.isBlank(String.valueOf(jo.get(name)))) {
                ro.setMessage("子参数中缺失参数[" + name + "]");
                ro.setResult(500);
                return ro;
            }
        }

        T t2 = JSON.parseObject(str, classType);

        ro.setResult(200);
        ro.setMessage("success");


        try {
            BeanUtils.copyProperties(t, t2);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
        }

        return ro;
    }

    /**
     * 获取分页SQL
     *
     * @param pageNum 页码
     * @return 返回分页SQL
     */
    public static String getPageSQL(int pageNum, int pageSize) {
        return " limit " + (pageSize * (pageNum - 1)) + ", " + pageSize;
    }


    /**
     * 将小程序传过来的地址，转换成web端的地址
     *
     * @param resAddress w原地址
     * @return 新地址
     */
    public static String convertAddress(String resAddress) {
        if (cn.net.isir.utils.StringUtils.isBlank(resAddress)) {
            return resAddress;
        }
        //["山东省","枣庄市","市中区"]
        resAddress = resAddress.replace("[\"", "");
        resAddress = resAddress.replace("\"]", "");
        return resAddress.replace("\",\"", "-");
    }

    /**
     * 判断新增/更新的时候，是否所需字段都必填
     *
     * @param o 实体类
     * @return 结果
     */
    public static ResultObject checkField(Object o, Class typeClass) {
        ResultObject ro = new ResultObject();
        if (o == null) {
            ro.setResult(500);
            ro.setMessage("所有字段都为空");
            return ro;
        }
        java.lang.reflect.Field[] fields = o.getClass().getDeclaredFields();
        //循环所有字段
        for (java.lang.reflect.Field field : fields) {
            //判断当前字段是否有SetBasicDao注解
            boolean fieldHasAnno = field.isAnnotationPresent(typeClass);
            //如果没有注解，不进行处理
            if (!fieldHasAnno) {
                continue;
            }
            //判断当前注解的字段，是否是BaseDao的子类，不是则不进行处理
//            if (!BasicDao.class.isAssignableFrom(field.getType())) {
//                continue;
//            }
            //设置可访问性，如果不设置，访问的时候会抛出不可读异常
            field.setAccessible(true);
            //获取字段的值
            Object val = null;
            try {
                val = field.get(o);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            logger.info("insertCheckField:" + field.getName());
            logger.info(field.getName() + ":" + val);
            //判断是否为空
            if (val == null || cn.net.isir.utils.StringUtils.isBlank(JSON.toJSONString(val))) {
                ro.setResult(500);
                ro.setMessage("字段[" + field.getName() + "]的值为空");
                return ro;
            }
        }
        ro.setResult(200);
        return ro;
    }

    public static void main(String[] args) {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("unionid", "o3Syb1ezZLUgScHsxQrpDcT0RQfY");
        jsonObject.put("fee", "1");
        String reqStr = Base64.getEncoder().encodeToString(jsonObject.toJSONString().getBytes());
        logger.info(reqStr);
    }
}
